/**
 * 
 */
package rs.fon.rapidminer.operator.learner.tree;

import java.util.List;

import com.rapidminer.example.Attribute;
import rs.fon.rapidminer.operator.learner.tree.SplittedExampleSet;
import rs.fon.rapidminer.operator.learner.tree.FrequencyCalculator;
import rs.fon.rapidminer.operator.learner.tree.InforamtionGainSplit;

import rs.fon.rapidminer.process.annotation.Parameter;

/**
 * @author Nikola
 * 
 */
public class GiniIndexSplit extends AbstractSplit {
	
	
	Attribute bestAttribute;
	int bestAttributeInt;
	SplittedExampleSet bestSplitted;
	double bestBenefit = -1;
	private FrequencyCalculator calculator = new FrequencyCalculator();	
	 
	@Override	
	public Object DoWork(List<SplittedExampleSet> sviSplitedi, List<rs.fon.rapidminer.process.Parameter> parameters)
	{
		int i = 0;
		
		for(SplittedExampleSet ses : sviSplitedi)
		{
			i++;
			double currentBenefit = -1;
			
			 double[] totalWeights = calculator.getLabelWeights(ses);
		        double totalWeight = calculator.getTotalWeight(totalWeights);
		        double totalEntropy = getGiniIndex(totalWeights, totalWeight);
		        double gain = 0;
		        for (int j = 0; j < ses.getNumberOfSubsets(); j++) {
		            ses.selectSingleSubset(j);
		            double[] partitionWeights = calculator.getLabelWeights(ses);
		            double partitionWeight = calculator.getTotalWeight(partitionWeights);
		            gain += getGiniIndex(partitionWeights, partitionWeight) * partitionWeight / totalWeight;
		        }
		    currentBenefit = totalEntropy - gain;
	        
	        if(currentBenefit > bestBenefit)
			{
				bestBenefit = currentBenefit;
				bestSplitted = ses;
				bestAttribute = ses.getAttribute();
			}		
		}   	
	
		return bestSplitted;		
	}
	
	 private double getGiniIndex(double[] labelWeights, double totalWeight) {
	    	double sum = 0.0d;
	    	for (int i = 0; i < labelWeights.length; i++) {
	    		double frequency = labelWeights[i] / totalWeight;
	    		sum += frequency * frequency;
	    	}
	    	return 1.0d - sum;
	    }
	 
	 @Override
	    public Object GetBenefit(SplittedExampleSet exampleSet) {
		 return null;
	 }
	
	@Override
	public Object GetBestAttribute(SplittedExampleSet exampleSet)
	{			
		return bestAttribute;
	}
		
	@Override
	public Object GetBenefit()	
	{
		return bestBenefit;
	}
}
